﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;


namespace WeiTap.Web
{
    /// <summary>
    /// 封装对某个属性的操作
    /// </summary>
    internal class PropertyHandler
    {
        /// <summary>
        /// 
        /// </summary>
        private readonly Action<object, object> _setter;
        /// <summary>
        /// 
        /// </summary>
        private readonly Func<object, object> _getter;
        /// <summary>
        /// 
        /// </summary>
        public Type PropertyType { get; }
        /// <summary>
        /// 
        /// </summary>
        public string Name { get; }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="p"></param>
        public PropertyHandler(PropertyInfo p)
        {
            Name = p.Name;
            PropertyType = p.DeclaringType;
            _getter = ReflectionHelper.GetGetter(p);
            _setter = ReflectionHelper.GetSetter(p);
        }

        public object GetValue(object instance)
        {
            if(_getter==null)
                throw new NotSupportedException("属性没有get方法或属性是只写的");
            return _getter(instance);
        }

        public void SetValue(object instance, object value)
        {
            if(_setter==null)
                throw new NotSupportedException("属性没有set方法或属性是只读的");
            if (PropertyType.IsInstanceOfType(value) == false)
            {
                try
                {
                    value = Convert.ChangeType(value, PropertyType);
                }
                catch (Exception e)
                {
                   throw new InvalidCastException(e.Message,e);
                }
                
            }
            _setter(instance, value);
        }
    }
}
